<template>
  <div class="dict-update-box">
    <el-form ref="form" v-loading="formLoading" :model="formData" :rules="rules" label-width="86px">
      <template v-for="item in formList">
        <el-form-item :key="item.prop" :label="item.name" :prop="item.prop">
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :select-style="selectStyle"
            :clearable="true"
            v-bind="item.attrConfig||{}"
          />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'

export default {
  name: 'AddDict',
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    },
    // 选中模块key
    selectParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      formLoading: false,
      formData: {
        label: '',
        value: '',
        sort: '',
        dictCode: '',
        name: '',
        remark: '',
        parentId: ''
      },
      formList: [
        { name: '所属字典',
          prop: 'dictCode',
          componentType: 'el-cascader',
          attrConfig: {
            disabled: true,
            placeholder: '请选择所属父字典',
            'show-all-levels': false,
            props: {
              children: 'children',
              label: 'name',
              value: 'id',
              checkStrictly: true
            },
            options: []
          }
        },
        { name: '字典名称',
          prop: 'name',
          attrConfig: {
            placeholder: '请输入字典名称'
          }
        },
        { name: '排序号',
          prop: 'sort',
          attrConfig: {
            placeholder: '请输入排序号',
            maxlength: 11
          }
        },
        { name: '备注',
          prop: 'remark',
          itemClass: 'width100p',
          attrConfig: {
            type: 'textarea',
            placeholder: '请输入备注信息',
            maxlength: 500
          }
        }
      ],
      selectStyle: {
        width: '100%'
      }
    }
  },
  computed: {
    rules() {
      return {
        name: [
          { required: true, message: '请输入字典名称', trigger: 'blur' },
          { required: true, message: '字典名称不能过长', max: 100, trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: this.sortRegs }
        ]
      }
    }
  },
  watch: {
    confirm: {
      handler(data) {
        if (data) {
          this.$nextTick(() => {
            const params = {
              ...this.formData || {}
            }
            this.submit(params)
          })
        }
      },
      deep: true,
      immediate: true
    },
    popData: {
      handler(data) {
        if (data) {
          this.formData = Object.assign({}, this.selectParams)
          this.formData.parentId = data.id
          this.formData.dictCode = data.id
          delete this.formData.parent
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    /**
     * 获取字典数据
    */
    getTreeData() {
      this.$api.dictManage.getDictModuleList({}).then(res => {
        if (Number(res.code) === 1000) {
          const treeList = arr2tree(res.data.records || [], { id: 'id', parentId: 'parentId' })
          this.formList.forEach(e => {
            if (e.prop === 'dictCode') {
              this.$set(e.attrConfig, 'options', treeList || [])
            }
          })
        } else if (res.msg) {
          this.$message({ type: 'error', message: res.msg })
        }
      })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$nextTick(() => {
        this.formLoading = true
        this.$refs.form.validate(async(valid) => {
          if (valid) {
            const res = await this.$api.dictManage.addDict(params)
            if (Number(res.code) === 1000 && res.data) {
              this.$message.success('新增成功!')
              this.$emit('onFinish', 'dict')
            } else if (res.msg) {
              this.$message({ type: 'error', message: res.msg })
            }
          }
        })
        this.formLoading = false
      })
    },
    /**
     * 排序号正则
     */
    sortRegs(rule, value, callback) {
      const REP = /^\d+$|^\d+[.]?\d+$/
      if (!REP.test(value)) {
        callback(new Error('您的排序号格式有误，请输入数字!'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dict-update-box {
  color: #333;
  padding: 0 20px;

  ::v-deep .el-cascader {
    width: 100%;
  }
}
</style>
